package com.wisdom.benefit.jufa.main;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import com.wisdom.benefit.jufa.R;
import com.wisdom.benefit.jufa.base.BaseApplication;
import com.wisdom.benefit.jufa.base.BaseNewFragment;
import com.wisdom.benefit.jufa.bean.HomeListBean;
import com.wisdom.benefit.jufa.event.CallBackInterface;
import com.wisdom.benefit.jufa.im.JWebSocketClient;
import com.wisdom.benefit.jufa.im.JWebSocketClientService;

import com.wisdom.benefit.jufa.net.RetrofitService;
import com.wisdom.benefit.jufa.utils.CommonDialog;
import com.wisdom.benefit.jufa.utils.CommonUtils;
import com.wisdom.benefit.jufa.utils.DataCleanManager;
import com.wisdom.benefit.jufa.utils.DialogUtil;
import com.wisdom.benefit.jufa.widget.Mylistview;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Timer;
import java.util.concurrent.TimeoutException;

import androidx.annotation.Nullable;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

import static android.content.Context.BIND_AUTO_CREATE;

public class HomeFragment extends BaseNewFragment implements SwipeRefreshLayout.OnRefreshListener, CallBackInterface {
    SwipeRefreshLayout refreshLayout;
    private TextView balanceTv, quotaTv, payMoneyTv, lineUoTv;//余额,账户余额，支付中金额,排队
    private Mylistview mylistview;
    private HomeAdapter homeAdapter;
    public static final String TAG = HomeFragment.class.getSimpleName();
    private TextView ineTv;
    private Button iveBtn;
    private JWebSocketClient client;
    private JWebSocketClientService.JWebSocketClientBinder binder;
    private JWebSocketClientService jWebSClientService;
    String appType;
    private Button btn_send;
    private ChatMessageReceiver chatMessageReceiver;
    private ArrayList<HomeListBean> datas;
    private int isChecked, isLineStatus;
    private double money;
    private String newOrder, oldOrder;
    private String userName = "tangchao_mq";
    private String passWord = "tangchao_mq";
    private String hostName = "116.140.34.174";
//        private String hostName = "122.10.18.183";
    private int portNum = 5672;
    private ConnectionFactory factory;
    private String exchangeName = "demo";
    private String rountingKey = "key";


    @Override
    public int setLayoutId() {
        return R.layout.fragment_home;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    /**
     * Rabbit配置
     */
    private void setupConnectionFactory() {
        factory = new ConnectionFactory();
        factory.setUsername(userName);
        factory.setPassword(passWord);
        factory.setHost(hostName);
        factory.setPort(portNum);

    }

    /**
     * 发消息
     */
    private void basicPublish() {

        try {
            //连接
            Connection connection = factory.newConnection();
            //通道
            Channel channel = connection.createChannel();
            //声明了一个交换和一个服务器命名的队列，然后将它们绑定在一起。
            channel.exchangeDeclare(exchangeName, "fanout", true);
            String queueName = "topic.recive.heart";
            channel.queueBind(queueName, exchangeName, rountingKey);
            //消息发布
            byte[] msg = "hello word!".getBytes();
            channel.basicPublish(exchangeName, rountingKey, null, msg);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }

    }

    /**
     * 收消息
     */
    private void basicConsume(final Handler handler) {

        try {
            //连接
            Connection connection = factory.newConnection();
            //通道
            final Channel channel = connection.createChannel();
            String queueName = "topic.payee.user_" + BaseApplication.getContext().getUserId();
            //实现Consumer的最简单方法是将便捷类DefaultConsumer子类化。可以在basicConsume 调用上传递此子类的对象以设置订阅：
            channel.basicConsume(queueName, false, new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    super.handleDelivery(consumerTag, envelope, properties, body);

                    String rountingKey = envelope.getRoutingKey();//路由密钥
                    String contentType = properties.getContentType();//contentType字段，如果尚未设置字段，则为null。
                    String msg = new String(body, "UTF-8");//接收到的消息
                    long deliveryTag = envelope.getDeliveryTag();//交付标记
                    channel.basicAck(deliveryTag, false);//手动消费
                    //从message池中获取msg对象更高效
                    Message uimsg = handler.obtainMessage();
                    Bundle bundle = new Bundle();
                    bundle.putString("msg", msg);
                    uimsg.setData(bundle);
                    handler.sendMessage(uimsg);
                }
            });

        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void findViewById(View view) {
        //下拉刷新
        refreshLayout = view.findViewById(R.id.refreshLayout);
        //列表
        mylistview = view.findViewById(R.id.home_lv);
        //余额明细
        balanceTv = view.findViewById(R.id.home_balance_tv);
        //账户余额
        quotaTv = view.findViewById(R.id.home_quota_tv);
        //排队
        lineUoTv = view.findViewById(R.id.home_line_up_tv);
        //支付中金额
        payMoneyTv = view.findViewById(R.id.home_pay_money_tv);
        //是否进入排队
        iveBtn = view.findViewById(R.id.home_ine_btn);
        ineTv = view.findViewById(R.id.home_ine_tv);
        Timer timer = new Timer();
        //连接设置
        setupConnectionFactory();
        //用于从线程中获取数据，更新ui
        final Handler incomingMessageHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                String message = msg.getData().getString("msg");
                setInfo(message);
            }
        };
        //开启消费者线程
        //subscribe(incomingMessageHandler);
        new Thread(new Runnable() {
            @Override
            public void run() {
                basicConsume(incomingMessageHandler);
            }
        }).start();
    }

    @Override
    public void setViewData(View view) {
        //自定义刷新控件颜色
        refreshLayout.setColorSchemeResources(R.color.blue);

    }


    @Override
    public void setClickEvent(View view) {
        //刷新
        refreshLayout.setOnRefreshListener(this);
        //余额
        balanceTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(getActivity(), DetailsBalanceActivity.class);
                startActivity(intent);
            }
        });
        iveBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isLineStatus == 0) {
                    Toast.makeText(getActivity(), "当前没有排队权限，请联系管理员", Toast.LENGTH_SHORT).show();
                } else {
                    if (isChecked == 1) {
                        outDialog();

                    } else {
                        if (TextUtils.isEmpty(appType)) {
                            Toast.makeText(getActivity(), "请开启收款码", Toast.LENGTH_SHORT).show();
                            isChecked = 0;
                        } else {
                            isChecked = 1;
                            updateStatus(BaseApplication.getContext().getUserId(), "1");
                        }
                    }
                }


            }
        });
        //是否进入排队
//        isLineUpSb.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
//
//            @Override
//            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//                if (isChecked) {
//                    if (TextUtils.isEmpty(a)) {
//                        Toast.makeText(getActivity(), "请开启收款码", Toast.LENGTH_SHORT).show();
//                        isLineUpSb.setChecked(false);
//                        return;
//                    } else {
//                        updateStatus(BaseApplication.getContext().getUserId(), "1");
//                        //启动服务
//                        startJWebSClientService();
//                        //绑定服务
//                        bindService();
//                        //注册广播
//                        doRegisterReceiver();
//                        BaseApplication.getContext().setIsHaveMa("");
//                    }
//                } else {
//                    updateStatus(BaseApplication.getContext().getUserId(), "0");
//                    jWebSClientService.closeConnect();
//                    lineUoTv.setText("未排队");
//                }
//            }
//        });
//        //自动确认到账
//        isGoBb.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
//
//            @Override
//            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//                if (isChecked) {
//                    BaseApplication.getContext().setIsGoAccount("1");
//                } else {
//                    BaseApplication.getContext().setIsGoAccount("0");
//                }
//            }
//        });
    }

    public static HomeFragment newInstance() {
        Bundle args = new Bundle();
        HomeFragment fragment = new HomeFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void onRefresh() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                refreshLayout.setVisibility(View.VISIBLE);
                refreshLayout.setRefreshing(false);
                appType = "";
                //相当于Fragment的onResume，为true时，Fragment已经可见
                userPassageway();
                findUser("");
                datas = new ArrayList<>();
            }
        }, 1000);
    }


    /**
     * 账号密码登陆
     */
    private void findUser(String msg) {
        showProgressDialog("");
        addDisposable(RetrofitService.getNetService()
                .findUser(BaseApplication.getContext().getUserId())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    hideProgressDialog();
                    if (response.getCode() == 0) {
                        quotaTv.setText(response.getData().getQuota());
                        payMoneyTv.setText(Double.toString(response.getData().getPayMoney()));
                        isChecked = response.getData().getLineUpStatus();
                        isLineStatus = response.getData().getLineStatus();
                        if (response.getData().getLineUpStatus() == 1) {
//                            updateStatus(BaseApplication.getContext().getUserId(), "1");
                            iveBtn.setText("退出排队");
                            iveBtn.setBackground(getResources().getDrawable(R.drawable.btn_red_shape));
                            if (TextUtils.isEmpty(msg)) {
                                ineTv.setText("已排队");
                            } else {
                                ineTv.setText(msg);
                            }

                            iveBtn.setClickable(true);
//                            //启动服务
//                            startJWebSClientService();
//                            //绑定服务
//                            bindService();
//                            //注册广播
//                            doRegisterReceiver();
                        } else {
//                            if (jWebSClientService.client.isClosed()) {
//
//                            } else {
//                                jWebSClientService.closeConnect();
//                            }
                            if (TextUtils.isEmpty(msg)) {
                                lineUoTv.setText("未排队");
                            } else {
                                lineUoTv.setText(msg);
                            }
                            iveBtn.setText("进入排队");
                            iveBtn.setClickable(true);
                            iveBtn.setBackground(getResources().getDrawable(R.drawable.btn_shape_blue));
                            ineTv.setText("是否进入排队");
                        }
                    } else {
                        showBindToast(response.getMsg());
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                    hideProgressDialog();

                }));
    }

    /**
     * 关闭按钮
     *
     * @param position
     */
    @Override
    public void callBackClick(int position) {
        if (datas.get(position).getStatus() == 0) {
            startDialog(datas.get(position).getPassagewayId());
//            editPassagewayStatus(datas.get(position).getPassagewayId(), 1);
        } else {
            closeDialog(datas.get(position).getPassagewayId());
//            editPassagewayStatus(datas.get(position).getPassagewayId(), 0);
        }

    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            appType = "";
            //相当于Fragment的onResume，为true时，Fragment已经可见
            userPassageway();
            findUser("");
            datas = new ArrayList<>();

        } else {
            //相当于Fragment的onPause，为false时，Fragment不可见
        }
    }

    @Override
    public void callBackClickOther(int position, boolean isCheck) {

    }

    /**
     * 根据推送消息进行处理
     *
     * @param msg
     */
    private void setInfo(String msg) {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        // 转list
        MainBean myObject = gson.fromJson(msg, new TypeToken<MainBean>() {
        }.getType());
        String code = myObject.getCode();
        String message = myObject.getMsg();
        String data = myObject.getData();
        if (TextUtils.isEmpty(code)) {

        } else {
            if (code.equals("3")) {
                isChecked = 0;
                findUser(message);
            } else if (code.equals("1")) {
                //排队
                lineUoTv.setText(message);
            } else if (code.equals("2")) {
                Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                Ringtone rt = RingtoneManager.getRingtone(getActivity(), uri);
                rt.play();
                newOrder = data;
                if (TextUtils.isEmpty(oldOrder)) {
                    oldOrder = data;
                    final CommonDialog dialog1 = new CommonDialog(getActivity());
                    dialog1.setTitle("接收订单通知")
                            .setMessage(message)
                            .setSingle(true).setOnClickBottomListener(new CommonDialog.OnClickBottomListener() {
                        @Override
                        public void onPositiveClick() {
                            dialog1.dismiss();
                            findUser("");
                        }

                        @Override
                        public void onNegtiveClick() {

                        }
                    }).show();
                } else {
                    if (oldOrder.equals(newOrder)) {

                    } else {
                        oldOrder = data;
                        final CommonDialog dialog1 = new CommonDialog(getActivity());
                        dialog1.setTitle("接收订单通知")
                                .setMessage(message)
                                .setSingle(true).setOnClickBottomListener(new CommonDialog.OnClickBottomListener() {
                            @Override
                            public void onPositiveClick() {
                                dialog1.dismiss();
                                findUser("");
                            }

                            @Override
                            public void onNegtiveClick() {

                            }
                        }).show();
                    }
                }
            } else if (code.equals("999")) {
                //开启消费者线程
//                subscribe(incomingMessageHandler);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        basicPublish();
                    }
                }).start();
            }
        }
    }

    /**
     * websocket推送接收
     */
    private class ChatMessageReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
//            String code = intent.getStringExtra("code");
//            String message = intent.getStringExtra("message");
//            String data = intent.getStringExtra("data");
//            Log.e("JWebSocketClient", "home收到的消息：" + message);
//            if (TextUtils.isEmpty(code)) {
//
//            } else {
//                if (code.equals("3")) {
//                    isChecked = 0;
//                    findUser(message);
////                    updateStatus(BaseApplication.getContext().getUserId(), "0");
////                    jWebSClientService.closeConnect();
////                    lineUoTv.setText(message);
////                    iveBtn.setText("进入排队");
////                    iveBtn.setClickable(false);
////                    iveBtn.setBackground(getResources().getDrawable(R.drawable.btn_shape_blue));
////                    ineTv.setText("是否进入排队");
//                } else if (code.equals("1")) {
////                if (chatMessageReceiver != null) {
////                    getActivity().unregisterReceiver(chatMessageReceiver);
////                    chatMessageReceiver = null;
////                }
//                    //排队
//                    lineUoTv.setText(message);
//                } else if (code.equals("2")) {
//                    Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
//                    Ringtone rt = RingtoneManager.getRingtone(getActivity(), uri);
//                    rt.play();
//                    newOrder = data;
//                    if (TextUtils.isEmpty(oldOrder)) {
//                        oldOrder = data;
//                        final CommonDialog dialog1 = new CommonDialog(getActivity());
//                        dialog1.setTitle("接收订单通知")
//                                .setMessage(message)
//                                .setSingle(true).setOnClickBottomListener(new CommonDialog.OnClickBottomListener() {
//                            @Override
//                            public void onPositiveClick() {
//                                dialog1.dismiss();
//                                findUser("");
//                            }
//
//                            @Override
//                            public void onNegtiveClick() {
//
//                            }
//                        }).show();
//                    } else {
//                        if (oldOrder.equals(newOrder)) {
//
//                        } else {
//                            oldOrder = data;
//                            final CommonDialog dialog1 = new CommonDialog(getActivity());
//                            dialog1.setTitle("接收订单通知")
//                                    .setMessage(message)
//                                    .setSingle(true).setOnClickBottomListener(new CommonDialog.OnClickBottomListener() {
//                                @Override
//                                public void onPositiveClick() {
//                                    dialog1.dismiss();
//                                    findUser("");
//                                }
//
//                                @Override
//                                public void onNegtiveClick() {
//
//                                }
//                            }).show();
//                        }
//                    }
//                }
//            }

        }
    }

    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            Log.e("HomeFragment", "服务与活动成功绑定");
            binder = (JWebSocketClientService.JWebSocketClientBinder) iBinder;
            jWebSClientService = binder.getService();
            client = jWebSClientService.client;
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            Log.e("HomeFragment", "服务与活动成功断开");
        }
    };

    /**
     * 更新排队状态
     */
    private void updateStatus(String userId, String status) {
        String deviceId = DeviceInfoModel.getDeviceId(getActivity());
        showProgressDialog("");
        addDisposable(RetrofitService.getNetService()
                .updateStatus(userId, status, deviceId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    hideProgressDialog();
                    if (response.getCode() == 0) {
                        if (status.equals("1")) {
                            iveBtn.setText("退出排队");
                            iveBtn.setBackground(getResources().getDrawable(R.drawable.btn_red_shape));
                            ineTv.setText("已排队");
                            iveBtn.setClickable(true);
//                            //启动服务
//                            startJWebSClientService();
//                            //绑定服务
//                            bindService();
//                            //注册广播
//                            doRegisterReceiver();
                        }
                    } else if (response.getCode() == -2) {
                        logout(BaseApplication.getContext().getUserId());
                        showBindToast(response.getMsg());
                    } else {
                        isChecked = 0;
                        iveBtn.setText("进入排队");
                        lineUoTv.setText(response.getMsg());
                        iveBtn.setBackground(getResources().getDrawable(R.drawable.btn_shape_blue));
                        ineTv.setText("是否进入排队");
//                        if (jWebSClientService != null) {
//                            if (jWebSClientService.client.isClosed()) {
//
//                            } else {
//                                jWebSClientService.closeConnect();
//                            }
//                        }
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                    hideProgressDialog();
                    showBindToast("无网络连接，请稍后再试");
                }));
    }

    /**
     * 推出登陆
     */
    private void logout(String userId) {
        showProgressDialog("");
        addDisposable(RetrofitService.getNetService()
                .logout(userId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    hideProgressDialog();
                    if (response.getCode() == 0) {
                        //步骤1：创建一个SharedPreferences对象
                        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("data", Context.MODE_PRIVATE);
                        //步骤2： 实例化SharedPreferences.Editor对象
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        //步骤3：将获取过来的值放入文件
                        editor.putString("isHaveLogin", "0");
                        //步骤4：提交
                        editor.commit();
                        BaseApplication.getContext().setDeviceId("");
                        Intent intent = new Intent(getActivity(), LoginActivity.class);
                        startActivity(intent);
                        getActivity().finish();
                    } else {
                        showBindToast(response.getMsg());
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                    hideProgressDialog();
                    if (CommonUtils.isNetworkAvailable(getContext()))
                        showBindToast("退出失败");
                    else
                        showBindToast("无网络连接，请稍后再试");
                }));
    }


    /**
     * 获取当前固态通道
     */
    private void userPassageway() {
        showProgressDialog("");
        addDisposable(RetrofitService.getNetService()
                .userPassageway(Long.valueOf(BaseApplication.getContext().getUserId()).longValue())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    hideProgressDialog();
                    if (response.getCode() == 0) {
                        datas = new ArrayList<>();
                        datas = response.getData();
                        for (int i = 0; i < datas.size(); i++) {
                            if (!TextUtils.isEmpty(datas.get(i).getPaymentCodePayeeName())) {
                                appType = "1";
                            }
                        }
                        //列表
                        homeAdapter = new HomeAdapter(datas, getActivity(), this);
                        mylistview.setAdapter(homeAdapter);
                    } else {
                        datas = new ArrayList<>();
                        //列表
                        homeAdapter = new HomeAdapter(datas, getActivity(), this);
                        mylistview.setAdapter(homeAdapter);
                        showBindToast(response.getMsg());
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                    hideProgressDialog();
                    if (CommonUtils.isNetworkAvailable(getContext()))
                        showBindToast("获取固码数据失败");
                    else
                        showBindToast("无网络连接，请稍后再试");
                }));
    }

    /**
     * 关闭/开启当前通道
     */
    private void editPassagewayStatus(Long codeId, int receivingAccount) {
        showProgressDialog("");
        addDisposable(RetrofitService.getNetService()
                .editPassagewayStatus(Long.valueOf(BaseApplication.getContext().getUserId()).longValue(), codeId, receivingAccount)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    hideProgressDialog();
                    if (response.getCode() == 0) {
                        findUser("");
                        userPassageway();
                    } else {
                        showBindToast(response.getMsg());
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                    hideProgressDialog();
                    if (CommonUtils.isNetworkAvailable(getContext()))
                        showBindToast("更改状态失败");
                    else
                        showBindToast("无网络连接，请稍后再试");
                }));
    }


    /**
     * 绑定服务
     */
    private void bindService() {
        Intent bindIntent = new Intent(getActivity(), JWebSocketClientService.class);
        getActivity().bindService(bindIntent, serviceConnection, BIND_AUTO_CREATE);
    }

    /**
     * 启动服务（websocket客户端服务）
     */
    private void startJWebSClientService() {
        Intent intent = new Intent(getActivity(), JWebSocketClientService.class);
        getActivity().startService(intent);
    }

    /**
     * 动态注册广播
     */
    private void doRegisterReceiver() {
        chatMessageReceiver = new ChatMessageReceiver();
        IntentFilter filter = new IntentFilter("com.xch.servicecallback.content");
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_SCREEN_ON);
        getActivity().registerReceiver(chatMessageReceiver, filter);
    }

    /**
     * 切换通道(打开)
     */
    private void startDialog(Long codeId) {
        DialogUtil dialogUtil = new DialogUtil(getActivity(), getActivity());
        dialogUtil.dialog("提示", "确定使用此通道？", "取消", "确定", "1");
        dialogUtil.setOnItemClickListener(new DialogUtil.OnItemClickListener() {
            @Override
            public void onItemCancelClick() {
                Log.d("onItemClick", "你点击了取消");
            }

            @Override
            public void onItemConfirmClick() {


            }

            @Override
            public void onItemValueConfirmClick(String a) {
                boolean b = DataCleanManager.clearAllCache(getActivity());
                if (b == true) {
                    editPassagewayStatus(codeId, 1);
                }
            }
        });
    }

    /**
     * 切换通道(关闭)
     */
    private void closeDialog(Long codeId) {
        DialogUtil dialogUtil = new DialogUtil(getActivity(), getActivity());
        dialogUtil.dialog("提示", "确定禁用此通道？", "取消", "确定", "1");
        dialogUtil.setOnItemClickListener(new DialogUtil.OnItemClickListener() {
            @Override
            public void onItemCancelClick() {
                Log.d("onItemClick", "你点击了取消");
            }

            @Override
            public void onItemConfirmClick() {


            }

            @Override
            public void onItemValueConfirmClick(String a) {
                boolean b = DataCleanManager.clearAllCache(getActivity());
                if (b == true) {
                    editPassagewayStatus(codeId, 0);
                }
            }
        });
    }

    /**
     * 退出排队
     */
    private void outDialog() {
        DialogUtil dialogUtil = new DialogUtil(getActivity(), getActivity());
        dialogUtil.dialog("提示", "确定退出排队？", "取消", "确定", "1");
        dialogUtil.setOnItemClickListener(new DialogUtil.OnItemClickListener() {
            @Override
            public void onItemCancelClick() {
                Log.d("onItemClick", "你点击了取消");
            }

            @Override
            public void onItemConfirmClick() {


            }

            @Override
            public void onItemValueConfirmClick(String a) {
                boolean b = DataCleanManager.clearAllCache(getActivity());
                if (b == true) {
                    isChecked = 0;
                    iveBtn.setText("进入排队");
                    iveBtn.setBackground(getResources().getDrawable(R.drawable.btn_shape_blue));
                    ineTv.setText("是否进入排队");
                    updateStatus(BaseApplication.getContext().getUserId(), "0");
                    userPassageway();
//                        jWebSClientService.closeConnect();
                    lineUoTv.setText("未排队");
                }
            }
        });
    }
}
